#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "mysem.h"

#define LEFT 	30000000
#define RIGHT 	30000200
#define THRNUM 	(RIGHT - LEFT + 1)
#define N 		4

static mysem_t * sem;

//线程处理函数
static void * the_primer(void * p)
{
	int i = (int)p;
	int j;
	int mark = 1;
	//判断质数
	for(j = 2; j < i / 2; j ++)
	{
		if(i % j == 0)
			{
				mark = 0;
				break;
			}
	}
	if(mark == 1)
		printf("%d is a primer\n", i);

    sleep(3);//可以查看线程号不断地更迭
	//信号量+1
    mysem_add(sem, 1);
	//线程结束
	pthread_exit(NULL);
}

int main()
{
	int i, err;
	pthread_t tid[THRNUM];

	//初始化信号量
    sem = mysem_init(N);
    if(sem == NULL)
    {
        fprintf(stderr, "seminit failed\n");
        exit(1);
    }
	//创建线程
	for(i = LEFT; i <= RIGHT; i++)
	{
		//信号量-1
        mysem_sub(sem, 1);
		//创建线程
		err = pthread_create(&tid[i - LEFT], NULL, the_primer, (void*)i);
		if(err)
		{
			fprintf(stderr, "create:%s", strerror(err));
			exit(0);
		}
	}
	//回收线程
	for(i = LEFT; i <= RIGHT; i++)
	{
		err = pthread_join(tid[i - LEFT], NULL);
	}
	//销毁信号量
    mysem_destroy(sem);

	exit(0);
}